<template>
  <view class="container">
    <div class="card-box" v-for="(item, index) in articleList" :key="item.id" @click="handleClick(item.id)">
      <van-card :desc="shortenedContent(item.content)" :title="item.title"
        :thumb="item.imageUrl">
        <view slot="footer">
          <span>{{formatTime(item.createTime)}}</span>
        </view>
      </van-card>
    </div>

  </view>
</template>

<script>
  import {
    getRecommendedArticles
  } from '@/api/article.js'

  export default {
    data() {
      return {
        articleList: [],
        userId: 0
      }
    },
    created() {
      this.userId = uni.getStorageSync('userId')
      this.fetchData()
    },
    onPullDownRefresh() {
      this.fetchData()
      uni.stopPullDownRefresh()
    },
    methods: {
      handleClick(id){
        uni.navigateTo({
        	url: `/pages/articles/article?id=${id}`
        });
      },
      fetchData() {
        getRecommendedArticles(this.userId).then((res) => {
          this.articleList = res.data
        })
      },
      shortenedContent(content) {
        return content.length > 50 ? content.slice(0, 50) + '...' : this.content;
      },
      formatTime(dateStr) {
        const time = new Date(dateStr)
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}.${month}.${day}`;
      },
    }
  }
</script>

<style scoped>
  .container {
    padding: 10px;
  }

  .card-box {
    margin-bottom: 10px;
  }
</style>